from flask import current_app, Blueprint, render_template, flash, redirect, url_for, request
from app.forms.login import LoginForm
from app.models.user import User
from app import db
from app.helpers import is_safe_url
from flask_login import login_user, logout_user


bp = Blueprint('auth', __name__)


@bp.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()

        if user is None or not user.validate_password(form.password.data):
            flash('账号或密码错误！', 'warning')
            return redirect(url_for('auth.login'))

        if user.role_id != 2:
            flash('没有权限，只有管理员才能登陆！', 'warning')
            return redirect(url_for('auth.login'))

        if user.status != 100:
            flash('账号未审核!', 'warning')
            return redirect(url_for('auth.login'))

        if login_user(user, remember=form.remember_me.data):
            flash('登陆成功!', 'success')
            current_app.logger.info('{}登陆成功'.format(form.username.data))
            user.last_ip = request.remote_addr
            db.session.commit()
            next_page = request.args.get('next')
            if is_safe_url(next_page):
                return redirect(next_page or url_for('site.index'))
        else:
            flash('账号异常！', 'warning')
            return redirect(url_for('auth.login'))

    return render_template('admin/auth/login.html', form=form)


@bp.route('/logout')
def logout():
    logout_user()
    flash('退出成功', 'success')
    return redirect(url_for('auth.login'))
